package main

import (
    "time"
    "fmt"
)

type StoreSet []Store

func (sm StoreSet) FilterByTable(appid, tableName string) StoreSet {
    var ret []Store
    for _, s := range sm {
        if s.GetTableDef().Appid == appid && s.GetTableDef().TableName == tableName {
            ret = append(ret, s)
        }
    }
    return StoreSet(ret)
}

func (sm StoreSet) FilterByPartition(partition, dt_prefix string) StoreSet {
    var ret []Store
    for _, s := range sm {
        if s.GetPartition().Filter(partition, dt_prefix) {
            ret = append(ret, s)
        }
    }
    return StoreSet(ret)
}

func (sm StoreSet) FilterByActive(o, r, w int64) StoreSet {
    var ret []Store
    now := time.Now().Unix()
    for _, s := range sm {
        ot, rt, wt := s.LastActiveTime()
        if (o != 0 && now-ot > o) || (r != 0 && now-rt > o) || (w != 0 && now-wt > w) {
            ret = append(ret, s)
        }
    }
    return StoreSet(ret)
}

func (sm StoreSet) GetOrCreate(td TableDefine, par Partition) (Store,error) {
    if td.DtLength != len(par.dt) {
        return nil,fmt.Errorf("td length not match")
    }
    subset := sm.FilterByTable(td.Appid, td.TableName)
    if len(subset) != 0 && !td.IsSame(subset[0].GetTableDef()) {
        return nil,fmt.Errorf("existing table define not match")
    }
    subset = subset.FilterByPartition(par.partition, par.dt)
    switch  len(subset) {
    case 0:
        s, err := NewRocksdbStore(td, par)
        if err != nil {
            return nil,err
        }
        sm = append(sm, s)
        return s,nil
    case 1:
        return subset[0],nil
    default:
        return nil,fmt.Errorf("existing duplicated partition found")
    }
}
